

#include "packet_count.hpp"
#include <cstdlib>

extern "C" {

    #include <libavformat/avformat.h>
    #include <libavcodec/avcodec.h>
    #include <libavcodec/packet.h>
}

int OutputPacketCount(const std::string &file_name) {

    AVFormatContext * format_ctx = NULL;

    int result = avformat_open_input(&format_ctx, file_name.c_str(), NULL, NULL);
    if (result < 0) {

        std::cout << "Error: avformat open input result : " << result << std::endl;
        return EXIT_FAILURE;
    }
    avformat_find_stream_info(format_ctx, NULL);
    av_dump_format(format_ctx, 0, file_name.c_str(), 0);
    std::cout << std::endl;

    int audio_index = 0;    
    int video_index = 0;

    for (int index = 0; index < format_ctx->nb_streams; index++) {

        AVStream * stream = format_ctx->streams[index];
        if (stream->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {

            video_index = index;
        } else if (stream->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {

            audio_index = index;
        }
    }

    AVPacket * packet = av_packet_alloc();

    int index = 0;

    int nb_audio_frames = 0;
    int nb_video_frames = 0;

    while(av_read_frame(format_ctx, packet) >= 0) {

        std::cout << "data size : " << packet->size << "\tindex : " << index << std::endl;
        index++;

        if (packet->stream_index == audio_index) {

            nb_audio_frames++;
        } else if (packet->stream_index == video_index) {

            nb_video_frames++;
        }
        av_packet_unref(packet);
    }
    std::cout << "total frame     : " << index << std::endl;
    std::cout << "nb video frames : " << nb_video_frames << std::endl;
    std::cout << "nb audio frames : " << nb_audio_frames << std::endl;

    av_packet_unref(packet);
    av_packet_free(&packet);
    avformat_free_context(format_ctx);

    return EXIT_SUCCESS;
}